﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace BaseHelper.Encrypt
{
    public class AesHelper
    {
        //应用实例
        //String encryptData = Program.Encrypt("Test String", "1234567812345678", "1234567812345678");
        //Console.WriteLine(encryptData);

        //String decryptData = Program.Decrypt("2fbwW9+8vPId2/foafZq6Q==", "1234567812345678", "1234567812345678");
        //Console.WriteLine(decryptData);

        public static string Key;

        //加密
        public static string Encrypt(string toEncrypt,string iv)
        {
            return Encrypt(toEncrypt, Key, iv);
        }

        public static string Encrypt(string toEncrypt, string key, string iv)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv);
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.IV = ivArray;
            rDel.Mode = CipherMode.CBC;
            rDel.Padding = PaddingMode.Zeros;
            ICryptoTransform cTransform = rDel.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            cTransform.Dispose();
            //rDel.Dispose();
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        //解密
        public static string Decrypt(string toDecrypt,byte[] iv)
        {
            //string iv =  //Random16();
            return Decrypt(toDecrypt, Key, iv);
        }

        public static string Decrypt(string toDecrypt, string key, byte[] iv)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            byte[] ivArray = iv;// UTF8Encoding.UTF8.GetBytes(iv);
            byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);
            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.IV = ivArray;
             rDel.Mode = CipherMode.CBC;
            rDel.Padding = PaddingMode.Zeros;
            ICryptoTransform cTransform = rDel.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);


            cTransform.Dispose();
            //rDel.Dispose();
            return UTF8Encoding.UTF8.GetString(resultArray);
        }

        public static string RandomIV()
        {
            string str= DateTime.Now.Ticks.ToString() + new Random().Next(10000000).ToString();
            return str.Substring(str.Length - 16, 16);
        }


    }
}
